"use client"

import { useState } from "react"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Loader2 } from "lucide-react"

// 定义配置选项的接口
interface ConfigOption {
  id: string
  label: string
  type: "number" | "select" | string
  defaultValue?: any
  min?: number
  max?: number
  step?: number
  options?: string[]
  optionLabels?: Record<string, string>
}

// 定义组件的Props接口
interface AlgorithmFormProps {
  configOptions: ConfigOption[]
  onSubmit: (formData: Record<string, any>) => void
  loading: boolean
}

export default function AlgorithmForm({ configOptions, onSubmit, loading }: AlgorithmFormProps) {
  const [formData, setFormData] = useState<Record<string, any>>(() => {
    return configOptions.reduce((acc: Record<string, any>, option: ConfigOption) => {
      acc[option.id] = option.defaultValue !== undefined ? option.defaultValue : ""
      return acc
    }, {})
  })

  const handleChange = (id: string, value: any) => {
    setFormData((prev: Record<string, any>) => ({
      ...prev,
      [id]: value,
    }))
  }

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault()
    onSubmit(formData)
  }

  return (
    <form onSubmit={handleSubmit} className="space-y-4">
      {configOptions.map((option: ConfigOption) => (
        <div key={option.id} className="space-y-2">
          <Label htmlFor={option.id}>{option.label}</Label>
          
          {option.type === "number" && (
            <Input
              id={option.id}
              type="number"
              value={formData[option.id]}
              onChange={(e) => handleChange(option.id, parseFloat(e.target.value))}
              min={option.min}
              max={option.max}
              step={option.step}
              disabled={loading}
            />
          )}
          
          {option.type === "select" && option.options && (
            <Select
              value={formData[option.id]}
              onValueChange={(value) => handleChange(option.id, value)}
              disabled={loading}
            >
              <SelectTrigger id={option.id}>
                <SelectValue placeholder="选择..." />
              </SelectTrigger>
              <SelectContent>
                {option.options.map((opt: string) => (
                  <SelectItem key={opt} value={opt}>
                    {option.optionLabels?.[opt] || opt}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          )}
        </div>
      ))}
      
      <Button type="submit" disabled={loading} className="w-full">
        {loading ? (
          <>
            <Loader2 className="mr-2 h-4 w-4 animate-spin" /> 正在执行...
          </>
        ) : (
          "执行算法"
        )}
      </Button>
    </form>
  )
} 